package com.tsoj.tsojuserservice.controller;

import com.baomidou.mybatisplus.extension.conditions.query.QueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.tsoj.common.BaseResponse;
import com.tsoj.common.ErrorCode;
import com.tsoj.common.ResultUtils;
import com.tsoj.exception.BusinessException;
import com.tsoj.model.dto.user.*;
import com.tsoj.model.po.User;
import com.tsoj.model.vo.LoginUserVO;
import com.tsoj.model.vo.UserVO;
import com.tsoj.propertise.JwtPropertise;
import com.tsoj.propertise.MaxPageSizePropertise;
import com.tsoj.tsojuserservice.service.UserService;
import com.tsoj.utils.RedisUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.List;

@RestController
@RequestMapping("/")
@Slf4j
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private MaxPageSizePropertise maxPageSize;
    //登陆相关

    //注册
    @PostMapping("/register")
    @ApiOperation(value = "用户注册")
    public BaseResponse<Long> register(@RequestBody UserRegisterDto userRegisterDto){
        //参数验证
        if(userRegisterDto == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        long id = userService.registerUser(userRegisterDto);
        return ResultUtils.success(id);
    }
    //用户登录
    @PostMapping("/login")
    @ApiOperation(value = "用户登录")
    public BaseResponse<LoginUserVO> login(@RequestBody UserLoginDto loginDto){
        //参数校验
        if(loginDto == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        LoginUserVO loginUserVO = userService.login(loginDto);

        return ResultUtils.success(loginUserVO);
    }
    //todo 微信登录接口

    //得到登录用户
    @GetMapping("/getLonginUser")
    @ApiOperation(value = "得到登录用户")
    public BaseResponse<User> getLonginUser(){
        User user = userService.getLoginUser();
        return ResultUtils.success(user);
    }

    //退出登录
//    @PostMapping("/logout")
//    @ApiOperation(value = "用户退出")
    public BaseResponse logout(){

        return ResultUtils.success("退出成功");
    }
    @Autowired
    private JwtPropertise jwtPropertise;
    @Autowired
    private RedisUtils redisUtils;
    //退出登录
    @PostMapping("/logout")
    @ApiOperation(value = "用户退出")
    public BaseResponse logout1(HttpServletRequest request){
        String token = request.getHeader(jwtPropertise.getUserTokenName());
        redisUtils.delete(token);
        return ResultUtils.success("退出成功");
    }
    //增删改查

    //新增用户(管理员可用)
    @ApiOperation(value = "新增用户")
    @PostMapping("/addUser")
    public BaseResponse addUser(@RequestBody UserAddDto userAddDto){
        //参数合法校验
        if(userAddDto == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if(userAddDto.getUserAccount() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号为空");
        }
        //写库
        User user = new User();
        user.setUseraccount(userAddDto.getUserAccount());
        String hexPassword = DigestUtils.md5DigestAsHex("12345678".getBytes(StandardCharsets.UTF_8));
        user.setUserpassword(hexPassword);
        if(userAddDto.getUsername() != null){
            user.setUsername(userAddDto.getUsername());
        }
        if(userAddDto.getUseravatarurl() != null){
            user.setUseravatarurl(userAddDto.getUseravatarurl());
        }
        if(userAddDto.getUserprofile() != null) {
            user.setUserprofile(userAddDto.getUserprofile());
        }
        boolean save = userService.save(user);
        if(!save){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "新增用户失败");
        }
        return ResultUtils.success("新增用户成功");
    }


    //删除用户(管理员可用)
    @ApiOperation(value = "删除用户")
    @DeleteMapping("/deleteUser")
//   todo @AdminRequire
    public BaseResponse deleteUser(int id){
       if(id <= 0){
           throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不合法");
       }
       QueryChainWrapper<User> user = userService.query().eq("id", id);
       if(user == null){
           throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
       }
        boolean b = userService.removeById(id);
       if(!b){
           throw new BusinessException(ErrorCode.PARAMS_ERROR, "删除用户失败");
       }
        return ResultUtils.success("删除用户成功");
    }
    //修改
    @PostMapping("/updateUser")
    @ApiOperation(value = "修改用户信息")
    public BaseResponse updateUser(UserUpdateDto userUpdateDto){
        if(userUpdateDto == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        if(userUpdateDto.getId() == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id为空");
        }
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("id",userUpdateDto.getId());
        User user = new User();
        user.setId(userUpdateDto.getId());
        if(userUpdateDto.getUserName() != null){
//            userQueryWrapper.eq("username",userUpdateDto.getUserName());
            user.setUsername(userUpdateDto.getUserName());
        }
        if(userUpdateDto.getUserAvatar() != null){
//            userQueryWrapper.eq("useravatarurl",userUpdateDto.getUserAvatar());
            user.setUseravatarurl(userUpdateDto.getUserAvatar());
        }
        if(userUpdateDto.getUserProfile() != null){
//            userQueryWrapper.eq("userprofile",userUpdateDto.getUserProfile());
            user.setUserprofile(userUpdateDto.getUserProfile());
        }
        boolean update = userService.updateById(user);
        if(!update){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        return ResultUtils.success("修改用户成功");
    }
    //单个查询接口 管理员权限
    @ApiOperation(value = "查询单个用户信息(管理员)")
    @GetMapping("/getUser/{id}")
//   todo @AdminRequire
    public BaseResponse<User> getUser(@PathVariable("id") int id){
        if(id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不合法");
        }
        User user = userService.getById(id);
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        return ResultUtils.success(user);
    }
    //批量分页查询
    @ApiOperation(value = "批量分页查询(管理员)")
    @PostMapping("/listUser")
//   todo @AdminRequire
    public BaseResponse listUser(UserQueryDto userQueryDto){
        //当前页数
        long current = userQueryDto.getCurrent();
        //分页大小
        long pageSize = userQueryDto.getPageSize();
        Page<User> userPage = userService.page(new Page<>(current, pageSize),
                userService.getQueryWrapper(userQueryDto));

        return ResultUtils.success(userPage.getRecords());
    }

    //普通用户查询单个id <返回脱敏信息>
    @ApiOperation(value = "查询单个用户信息(普通用户)")
    @GetMapping("/get/vo/{id}")
    public BaseResponse<UserVO> getUserVO(@PathVariable("id") long id){
        if(id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "id不合法");
        }
        User user = userService.getById(id);
        if(user == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
        }
        UserVO userVO = new UserVO();
        BeanUtils.copyProperties(user,userVO);
        return ResultUtils.success(userVO);
    }
    //普通分页用户查询 <返回脱敏信息>
    @ApiOperation(value = "批量分页查询(普通用户)")
    @PostMapping("/list/vo")
    public BaseResponse<Page<UserVO>> listUserVO(UserQueryDto userQueryDto){
            if (userQueryDto == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            long current = userQueryDto.getCurrent();
            long size = userQueryDto.getPageSize();
            if(size > maxPageSize.getMaxPageSize()){
                throw new BusinessException(ErrorCode.DATA_GET_ERROR);
            }
            Page<User> userPage = userService.page(new Page<>(current, size),
                    userService.getQueryWrapper(userQueryDto));
            Page<UserVO> userVOPage = new Page<>(current, size, userPage.getTotal());
            List<UserVO> userVO = userService.getUserVO(userPage.getRecords());
            userVOPage.setRecords(userVO);
            return ResultUtils.success(userVOPage);
    }
}
